﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
using System.Threading;
using System.IO;

namespace NetworkResetor
{
    public partial class Form1 : Form
    {

        // 实例一个Process类,启动一个独立进程
        private Process p = new Process();
        private Thread checkerThread;
        public Form1()
        {
            InitializeComponent();

            // 设定程序名
            p.StartInfo.FileName = "cmd.exe";
            // 关闭Shell的使用
            p.StartInfo.UseShellExecute = false;
            // 重定向标准输入
            p.StartInfo.RedirectStandardInput = true;
            // 重定向标准输出
            p.StartInfo.RedirectStandardOutput = true;
            //重定向错误输出
            p.StartInfo.RedirectStandardError = true;
            // 设置不显示窗口
            p.StartInfo.CreateNoWindow = true;
            
        }

        public void Resetor() {
            // 启动进程并执行命令
            do
            {
                Thread.Sleep(7000);

                p.Start();

                p.StandardInput.WriteLine("ping 202.204.105.1");
                p.StandardInput.WriteLine("exit");

                //读取出输出结果
                StringBuilder rstBuilder = new StringBuilder();
                while (!p.StandardOutput.EndOfStream)
                {
                    rstBuilder.Append(p.StandardOutput.ReadLine() + "" + Environment.NewLine);
                }
                p.Close();

                int position = rstBuilder.ToString().IndexOf("%");
                string passRate = rstBuilder.ToString().Substring(position - 2, 3);
                bool ok = passRate[0].Equals('(') || passRate[0].Equals('2');//即丢包率为0%,25%可以认为通过测试
                
                if (!ok)
                {
                    writeLog(DateTime.Now + "  :  网络发生不畅通，开始重新设置IP");

                    SetNetworkAdapter("00:13:72:61:0C:50", "121.194.93.120");
                    Thread.Sleep(3000);
                    SetNetworkAdapter("00:13:72:61:0C:50", "121.194.93.121");
                }
            } while (true);            
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            checkerThread = new Thread(Resetor);
            checkerThread.Start();
            writeLog(DateTime.Now + "  :  开始网络重设保护");
        }
        
        public void SetNetworkAdapter(string MAC,string ip)
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                //if (!(bool)mo["IPEnabled"])
                //    continue;
                if ((bool)mo["IPEnabled"]&&mo["MACAddress"].ToString().Equals(MAC))
                {
                    //设置ip地址和子网掩码

                    inPar = mo.GetMethodParameters("EnableStatic");
                    inPar["IPAddress"] = new string[] { ip, ip };// 1.IP 2.备用
                    inPar["SubnetMask"] = new string[] { "255.255.255.0", "255.255.255.0" };
                    outPar = mo.InvokeMethod("EnableStatic", inPar, null);

                    //设置网关地址 
                    inPar = mo.GetMethodParameters("SetGateways");
                    inPar["DefaultIPGateway"] = new string[] { "121.194.93.254", "121.194.93.254" }; // 1.网关;2.备用网关
                    outPar = mo.InvokeMethod("SetGateways", inPar, null);

                    //设置DNS 
                    inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                    inPar["DNSServerSearchOrder"] = new string[] { "202.204.105.1", "202.204.105.5" }; // 1.DNS 2.备用DNS
                    outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                    break;
                }

            }
        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            checkerThread.Abort();
            writeLog(DateTime.Now + "  :  停止网络重设保护");
        }

        private void writeLog(string logLine){
                    FileStream fs = new FileStream(Application.StartupPath + "\\NetworkResetorLog.txt", FileMode.Append);
                    StreamWriter wr = new StreamWriter(fs);
                    wr.WriteLine(logLine);
                    wr.Flush();
                    wr.Close();
                    fs.Close();
                }
    }
}
